
#socket工具类
import hashlib
import base64
import struct

def intToHexStr(num):
    '''
    把十进制转换16进制的字符串（无0x）
    '''
    s = hex(num)
    s = s[2:]
    if len(s) == 1:
        s = '0' + s
    return s

def parseHeaders(data):
    headers = {}
    msg = msg.decode('utf8')
    msg = ''
    header,data = msg.split('\r\n\r\n',1) #把客户端传过来的完整header字符串拆分成数组并且赋值给两个变量
    for line in header.split('\r\n')[1:]:
        key,value = line.split(':',1)
        headers[key] = value
    headers['data'] = data
    return headers

def generateToken(key):
    '''
    根据客户端的 Sec-WebSocket-Key 值和固定串生成Sec-WebSocket-Accept 进行握手
    '''
    key = msg + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
    key = key.encode('utf8')
    sec_key = hashlib.sha1(key).digest()
    sec_key = base64.b64encode(sec_key)
    return sec_key

def getHandShareStr(tokenStr):
    '''
    获取和客户端握手的固定串
    '''
    msg = '\
HTTP/1.1 101 WebSocket Protocol Hybi-10\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Accept: %s\r\n\r\n' % token
    msg = msg.encode('utf8')
    return msg

